﻿
using S7Cat.Tools;
using System.Buffers.Binary;
using System.Net.Sockets;

namespace S7Cat.Protocol
{
    internal static class TPKT
    {
        public static async Task<MemoryOwner<byte>> ReadAsync(NetworkStream stream, CancellationToken cancellationToken)
        {
            //using var buffer = MemoryOwner<byte>.Allocate(4, AllocationMode.Clear);            
            //await stream.ReadExactlyAsync(buffer.Memory, cancellationToken).ConfigureAwait(false);
            //var len = BinaryPrimitives.ReadInt16BigEndian(buffer.Span.Slice(2));
            var buffer = new byte[4];
            await stream.ReadExactlyAsync(buffer, cancellationToken).ConfigureAwait(false);
            var len = BinaryPrimitives.ReadInt16BigEndian(buffer.AsSpan(2));

            if (len < 4)
            {
                throw new Exception("TPKT is incomplete / invalid");
            }

            var buffer2 = MemoryOwner<byte>.Allocate(len - 4, AllocationMode.Clear);
            await stream.ReadExactlyAsync(buffer2.Memory, cancellationToken).ConfigureAwait(false);

            return buffer2;
        }
    }
}
